package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.DimensionsKey;
import com.tanhua.model.mongo.*;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.Conclusions;
import com.tanhua.server.utils.Covers;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @Desciption:test
 * @Create by:金木yan
 * @Date: 2021/12/11 17:02
 */
@Service
public class TestSoulService {
    @DubboReference
    private QuestionnaireApi questionnaireApi;
    @DubboReference
    private SoulQuestionsApi soulQuestionsApi;
    @DubboReference
    private OptionsApi optionsApi;
    @DubboReference
    private QuestionnaireIsLockApi isLockApi;
    @DubboReference
    private QuestionnaireReportApi reportApi;
    @DubboReference
    private DimensionsApi dimensionsApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询问卷列表
     */
    public List<QuestionnaireVo> soulList() {
        //1.查询问卷列表
        List<Questionnaire> questionnaires = questionnaireApi.find();
        //2.判断
        if (CollUtil.isEmpty(questionnaires)) {
            return new ArrayList<>();
        }
        //3.从redis中获取数据
        String key = "isLock_" + UserHolder.getUserId();
        //判断是否给该用户设置了默认状态
        if (!redisTemplate.hasKey(key)) {
            //没有设置
            //4.设置当前用户默认问卷锁状态
            for (Questionnaire questionnaire : questionnaires) {
                //保存数据到问卷锁表中
                QuestionnaireIsLock isLock = new QuestionnaireIsLock();
                isLock.setQuestionnaireId(questionnaire.getId());
                isLock.setUserId(UserHolder.getUserId());
                if ("初级".equals(questionnaire.getLevel())) {
                    isLock.setIsLock(0);
                } else {
                    isLock.setIsLock(1);
                }
                isLock.setCreated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                isLock.setUpdated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                isLockApi.saveOrUpdate(isLock);
                //保存状态到redis中
                redisTemplate.opsForValue().set(key, "true");
            }
        }
        //5.遍历集合，封装为vo
        List<QuestionnaireVo> list = new ArrayList<>();
        for (Questionnaire questionnaire : questionnaires) {
            //5.1查询问卷锁状态
            QuestionnaireIsLock isLock = isLockApi.findByQuestionnaireId(questionnaire.getId(),UserHolder.getUserId());
            //5.2查询问卷报告
            QuestionnaireReport report = reportApi.findByQuestionnaireId(questionnaire.getId(),UserHolder.getUserId());
            //5.3查询试题集合
            Map<ObjectId, List<SoulQuestion>> map = soulQuestionsApi.findByQuestionnaireId(questionnaire.getId());
            List<SoulQuestion> soulQuestions = map.get(questionnaire.getId());
            //5.4调用方法，封装为SoulQuestionsVo
            List<SoulQuestionsVo> questionsVoList = getVoArrayList(soulQuestions);
            //5.5判断
            if (!CollUtil.isEmpty(questionsVoList)) {
                //封装为QuestionnaireVo
                QuestionnaireVo vo = QuestionnaireVo.init(questionnaire, questionsVoList);
                if (isLock != null) {
                    vo.setIsLock(isLock.getIsLock());
                }
                if (report != null) {
                    vo.setReportId(report.getId().toHexString());
                }
                list.add(vo);
            }
        }
        //6.返回
        return list;
    }


    /**
     * 查询试题vo集合
     */
    private List<SoulQuestionsVo> getVoArrayList(List<SoulQuestion> questions) {
        //1.创建questionsVoList集合
        List<SoulQuestionsVo> questionsVoList = new ArrayList<>();
        //2.遍历
        for (SoulQuestion question : questions) {
            //3.查询试题选项集合
            Map<ObjectId, List<Option>> map = optionsApi.findByQuestionId(question.getId());
            //4.构建SoulQuestionsVo
            if (!CollUtil.isEmpty(map)) {
                List<Option> options = map.get(question.getId());
                //构建optionVo
                List<OptionVo> list = new ArrayList<>();
                for (Option option : options) {
                    OptionVo optionVo = new OptionVo();
                    if (option != null) {
                        BeanUtils.copyProperties(option, optionVo);
                        optionVo.setId(option.getId().toHexString());
                        optionVo.setQuestionId(option.getQuestionId().toHexString());
                        list.add(optionVo);
                    }
                }
                SoulQuestionsVo vo = SoulQuestionsVo.init(question, list);
                questionsVoList.add(vo);
            }
        }
        //5.返回
        return questionsVoList;
    }

    /**
     * 根据id查询报告
     */
    public QuestionnaireReportVo findReport(String id) {
        //1.查询报告信息
        QuestionnaireReport report = reportApi.findById(id);
        if (report == null) {
            throw new BusinessException(ErrorResult.builder().errMessage("请您答题后再查看报告").build());
        }
        //2.查询维度dimensions列表
        List<Dimensions> dimensionsList = dimensionsApi.findByReportId(id);
        //3.查询相似用户信息similarYou---同一份问卷，总分在[-10,+10]之间的用户
        List<Long> ids = reportApi.findSimilarYou(id, report.getQuestionnaireId(), report.getTotalScore());
        List<SimilarYou> similarYouList = new ArrayList<>();
        if (!CollUtil.isEmpty(ids)) {
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
            for (Long userId : ids) {
                UserInfo userInfo = map.get(userId);
                if (userInfo != null) {
                    SimilarYou similarYou = SimilarYou.init(userInfo);
                    similarYouList.add(similarYou);
                }
            }
        }
        //4.封装vo
        QuestionnaireReportVo reportVo = QuestionnaireReportVo.init(report, dimensionsList, similarYouList);
        //5.返回
        return reportVo;
    }

    /**
     * 提交问卷
     */
    public String commit(Map map) {
        //1.获取参数
        List<Map> mapList = (List<Map>) map.get("answers");
        if (CollUtil.isEmpty(mapList)) {
            throw new BusinessException(ErrorResult.error());
        }
        //2.查询问卷id
        Map result = mapList.get(0);
        String qsId = (String) result.get("questionId");
        ObjectId questionnaireId = soulQuestionsApi.findById(qsId);
        //3.统计问卷总得分score
        int sum = 0;
        for (Map map1 : mapList) {
            String questionId = (String) map1.get("questionId");
            String optionId = (String) map1.get("optionId");
            //3.1查询该选项分数
            Integer score = optionsApi.findById(optionId);
            sum += score;
        }
        //4.保存问卷报告report
        //判断总分属于哪个范围，保存对应的conclusion
        int i = RandomUtil.randomInt(1, 12);
        String conclusion = Conclusions.get(i);
        //设置参数
        QuestionnaireReport report = new QuestionnaireReport();
        report.setUserId(UserHolder.getUserId());
        report.setConclusion(conclusion);
        report.setCover(Covers.get(i));
        report.setTotalScore(sum);
        report.setQuestionnaireId(questionnaireId);
        report.setCreated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        report.setUpdated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String reportId = reportApi.save(report);
        //5.保存维度数据dimensions
        for (int j = 1; j <= 4; j++) {
            //创建对象,设置属性值
            Dimensions dimensions = new Dimensions();
            dimensions.setReportId(new ObjectId(reportId));
            //通过自定枚举获取
            dimensions.setKey(DimensionsKey.getName(j));
            dimensions.setValue(RandomUtil.randomInt(60, 90) + "%");
            dimensions.setCreated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            dimensionsApi.save(dimensions);
        }
        //6.修改问卷状态
        //查询问卷
        Questionnaire questionnaire = questionnaireApi.findById(questionnaireId);
        QuestionnaireIsLock isLock = new QuestionnaireIsLock();
        if (!StringUtils.isEmpty(reportId)) {
            if ("初级".equals(questionnaire.getLevel())) {
                //初级问卷已做完，开启中级问卷
                ObjectId id = questionnaireApi.findByLevel("中级");
                isLock.setQuestionnaireId(id);
                isLock.setIsLock(0);
            } else if ("中级".equals(questionnaire.getLevel())) {
                //中级问卷已做完，开启高级问卷
                ObjectId id = questionnaireApi.findByLevel("高级");
                isLock.setQuestionnaireId(id);
                isLock.setIsLock(0);
            }
        }
        isLock.setUserId(UserHolder.getUserId());
        isLock.setUpdated(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        isLockApi.saveOrUpdate(isLock);
        //7.返回
        return reportId;
    }
}
